Telegram Group & Telegram Channel
🐍 Задача уровня Pro: декоратор с внутренним состоянием

📌 Задача:
Напиши декоратор call_limiter, который:

- ограничивает функцию f максимум до n вызовов
- после n вызова функция больше не вызывается, а возвращает строку "LIMIT REACHED"

Пример использования:


@call_limiter(3)
def greet(name):
return f"Hello, {name}!"

print(greet("Alice")) # Hello, Alice!
print(greet("Bob")) # Hello, Bob!
print(greet("Charlie"))# Hello, Charlie!
print(greet("Dave")) # LIMIT REACHED


🎯 Подвохи:
- Нужно создать декоратор-фабрику с аргументом n
- Внутри должна быть функция с nonlocal, чтобы отслеживать число вызовов
- Часто путаются и используют mutable default, что ломает независимость между декорируемыми функциями

Решение:

```python
def call_limiter(n):
def decorator(func):
count = 0
def wrapper(*args, **kwargs):
nonlocal count
if count >= n:
return "LIMIT REACHED"
count += 1
return func(*args, **kwargs)
return wrapper
return decorator
```

🧪 **Проверка:**

```python
@call_limiter(2)
def ping():
return "pong"

print(ping()) # pong
print(ping()) # pong
print(ping()) # LIMIT REACHED

@call_limiter(1)
def echo(msg):
return msg

print(echo("hi")) # hi
print(echo("bye")) # LIMIT REACHED
```

🧠 **Что проверяет задача:**

• Понимание функций высшего порядка
• Работа с `nonlocal` и областью видимости
• Контроль состояния внутри декоратора
• Умение не "засорить" глобальные или общие области





@Python_Community_ru



tg-me.com/Python_Community_ru/2604
Create:
Last Update:

🐍 Задача уровня Pro: декоратор с внутренним состоянием

📌 Задача:
Напиши декоратор call_limiter, который:

- ограничивает функцию f максимум до n вызовов
- после n вызова функция больше не вызывается, а возвращает строку "LIMIT REACHED"

Пример использования:


@call_limiter(3)
def greet(name):
return f"Hello, {name}!"

print(greet("Alice")) # Hello, Alice!
print(greet("Bob")) # Hello, Bob!
print(greet("Charlie"))# Hello, Charlie!
print(greet("Dave")) # LIMIT REACHED


🎯 Подвохи:
- Нужно создать декоратор-фабрику с аргументом n
- Внутри должна быть функция с nonlocal, чтобы отслеживать число вызовов
- Часто путаются и используют mutable default, что ломает независимость между декорируемыми функциями

Решение:

```python
def call_limiter(n):
def decorator(func):
count = 0
def wrapper(*args, **kwargs):
nonlocal count
if count >= n:
return "LIMIT REACHED"
count += 1
return func(*args, **kwargs)
return wrapper
return decorator
```

🧪 **Проверка:**

```python
@call_limiter(2)
def ping():
return "pong"

print(ping()) # pong
print(ping()) # pong
print(ping()) # LIMIT REACHED

@call_limiter(1)
def echo(msg):
return msg

print(echo("hi")) # hi
print(echo("bye")) # LIMIT REACHED
```

🧠 **Что проверяет задача:**

• Понимание функций высшего порядка
• Работа с `nonlocal` и областью видимости
• Контроль состояния внутри декоратора
• Умение не "засорить" глобальные или общие области





@Python_Community_ru

BY Python Community


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/Python_Community_ru/2604

View MORE
Open in Telegram


Python Community Telegram | DID YOU KNOW?

Date: |

That growth environment will include rising inflation and interest rates. Those upward shifts naturally accompany healthy growth periods as the demand for resources, products and services rise. Importantly, the Federal Reserve has laid out the rationale for not interfering with that natural growth transition.It's not exactly a fad, but there is a widespread willingness to pay up for a growth story. Classic fundamental analysis takes a back seat. Even negative earnings are ignored. In fact, positive earnings seem to be a limiting measure, producing the question, "Is that all you've got?" The preference is a vision of untold riches when the exciting story plays out as expected.

What Is Bitcoin?

Bitcoin is a decentralized digital currency that you can buy, sell and exchange directly, without an intermediary like a bank. Bitcoin’s creator, Satoshi Nakamoto, originally described the need for “an electronic payment system based on cryptographic proof instead of trust.” Each and every Bitcoin transaction that’s ever been made exists on a public ledger accessible to everyone, making transactions hard to reverse and difficult to fake. That’s by design: Core to their decentralized nature, Bitcoins aren’t backed by the government or any issuing institution, and there’s nothing to guarantee their value besides the proof baked in the heart of the system. “The reason why it’s worth money is simply because we, as people, decided it has value—same as gold,” says Anton Mozgovoy, co-founder & CEO of digital financial service company Holyheld.

Python Community from hk


Telegram Python Community
FROM USA